import { defineStore } from 'pinia';
import teamRoleApi from '@/api/teamKnowdge/teamRoleApi';

interface RoleData {
  rank: number;
  params?: string;
}

export const useTeamRoleStore = defineStore('teamRole', () => {
  // State
  const roleData = ref<RoleData>({ rank: 0 });
  const roleDataMenu = ref<RoleData>({ rank: 0 });
  const myRoleList = ref<string[]>([]);
  const myParentRoleList = ref<string[]>([]);
  const myTeamFileRoleList = ref<string[]>([]);
  const sharedData = ref<null | string>(null);

  // Mutations (using direct assignments or reactive updates)
  const setSharedData = (data: string) => {
    sharedData.value = data;
  };

  // Actions
  const getUserTeamRoleApi = async (params: Record<string, any>): Promise<void> => {
    try {
      const res = await teamRoleApi.apiTeamMemberQueryMemberRole(params);
      const firstRole = res.data?.[0];
      if (firstRole) {
        roleData.value = firstRole;
        roleDataMenu.value = firstRole;
        if (firstRole.params) {
          const parsedParams = JSON.parse(firstRole.params);
          myRoleList.value = parsedParams;
          myParentRoleList.value = parsedParams;
        }
      }
    } catch (error) {
      console.error('Error fetching user team role:', error);
      throw error;
    }
  };

  const getUserTeamFileRoleApi = ({ params, type }: { params: Record<string, any>; type?: 'parent' | 'current' }) => {
    return new Promise((resolve, reject) => {
      teamRoleApi
        .apiTeamRelevanceRoleQueryPermByUser(params)
        .then((res) => {
          if (res && res.data) {
            let dataToProcess: any[] = [];

            // 判断 res.data 是数组还是对象，进行不同处理
            if (Array.isArray(res.data)) {
              // 如果是数组，直接处理
              dataToProcess = res.data;
            } else if (typeof res.data === 'object') {
              // 如果是对象，假设对象可能只有一个角色，直接将对象转换为数组处理
              dataToProcess = [res.data];
            } else {
              console.warn('Unexpected data type:', typeof res.data);
            }

            // 如果 dataToProcess 里有数据，进行处理
            if (dataToProcess.length > 0) {
              let combinedParams: string[] = [];
              // 遍历返回的角色数据
              dataToProcess.forEach((roleData: RoleData) => {
                if (roleData.params) {
                  // 尝试解析 params 字符串为数组
                  try {
                    const parsedParams = JSON.parse(roleData.params);
                    combinedParams = combinedParams.concat(parsedParams);
                  } catch (e) {
                    console.error('Error parsing params:', e);
                  }
                }
              });

              // 去重处理
              combinedParams = Array.from(new Set(combinedParams.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item));

              // 根据类型更新对应的 state
              if (type === 'parent') {
                myParentRoleList.value = combinedParams;
              } else {
                myTeamFileRoleList.value = combinedParams;
              }
            } else {
              // 如果没有数据，可以选择清空对应的列表
              if (type === 'parent') {
                myParentRoleList.value = [];
              } else {
                myTeamFileRoleList.value = [];
              }
            }

            // 返回结果
            resolve(res);
          } else {
            console.warn('No data returned or invalid response structure.');
            resolve(res);
          }
        })
        .catch((error) => {
          console.error('Error fetching user team file role:', error);
          reject(error);
        });
    });
  };

  const fetchData = async (payload: Record<string, any>): Promise<string> => {
    try {
      const res = await teamRoleApi.apiTeamRoleQuery(payload);
      setSharedData(res.data.content);
      return res.data.content;
    } catch (error) {
      console.error('Error fetching data:', error);
      throw error;
    }
  };

  return {
    roleData,
    roleDataMenu,
    myRoleList,
    myParentRoleList,
    myTeamFileRoleList,
    sharedData,
    setSharedData,
    getUserTeamRoleApi,
    getUserTeamFileRoleApi,
    fetchData
  };
});
